package com.ruoyi.business.util;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.MonitorLog;
import com.ruoyi.bizsys.service.IMonitorLogService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.business.common.AsyncService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class BathJobMonitorUtil {

    @Autowired
    RedisCache redisCache;

    @Autowired
    ISysConfigService iSysConfigService;

    @Autowired
    IMonitorLogService iMonitorLogService;

    @Autowired
    AsyncService asyncService;

    private static BathJobMonitorUtil bathJobMonitorUtil;

   @PostConstruct
    public void init() {
        bathJobMonitorUtil = this;
        bathJobMonitorUtil.redisCache = this.redisCache;
        bathJobMonitorUtil.iSysConfigService = this.iSysConfigService;
        bathJobMonitorUtil.iMonitorLogService = this.iMonitorLogService;
    }

    public void clearRedis(String apiName){
        redisCache.deleteObject(apiName + BizConstants.MONITOR_LOGS);
        redisCache.deleteObject(apiName +BizConstants.MONITOR_COUNTNUMS);
        redisCache.deleteObject(apiName + BizConstants.MONITOR_FAILNUMS);
    }

    public void setRedis(String threadName,String identification,String error,String errorRemark) {

        //捕捉  以防出错影响主流程
        try{
            String key = null;
            String key1 = null;
            if(threadName.contains("BatchJobThread")){
                key = "BatchJob"+BizConstants.MONITOR_LOGS;
                key = "BatchJob"+BizConstants.MONITOR_FAILNUMS;
            }else if(threadName.contains("CollectionTask")){
                key = "CollectionTask"+BizConstants.MONITOR_LOGS;
                key1 = "CollectionTask"+BizConstants.MONITOR_FAILNUMS;
            }
            if(key==null){
                return;
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Identification", identification);
            jsonObject.put("Error", error);
            jsonObject.put("ErrorRemark", errorRemark);
            jsonObject.put("Time", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

            List<Object> newList = new ArrayList<>();
            newList.add(jsonObject);
            redisCache.setCacheList(key, newList);
            redisCache.setCacheObject(key1, redisCache.getCacheObject(key1)==null?1:Integer.parseInt(redisCache.getCacheObject(key1).toString())+1);
        }catch (Exception e){
            log.error("setRedis error", e);
        }
    }

    public void delRedis(String apiName){
        List<Object> cacheList = redisCache.getCacheList(apiName + BizConstants.MONITOR_LOGS);

        if(cacheList==null || cacheList.size()==0){
            return;
        }

        String startTime = "";
        String endTime = "";
        Integer successNums = redisCache.getCacheObject(apiName + BizConstants.MONITOR_COUNTNUMS);
        Integer failNums = redisCache.getCacheObject(apiName + BizConstants.MONITOR_FAILNUMS);
        for (int i = 0;i<cacheList.size();i++){
            JSONObject jsonObject = JSONObject.parseObject(cacheList.get(i).toString());
            if(i==0){
                startTime = jsonObject.getString("Time");
            }
            if(i==cacheList.size()-1){
                endTime = jsonObject.getString("Time");
            }
        }

        String s = IdUtils.reqId();

        String monitorName = "monitor-group";

        MonitorLog monitorLog = new MonitorLog();
        monitorLog.setApiName(apiName);
        monitorLog.setLogContent(cacheList.subList(0,cacheList.size()>15?15:cacheList.size()).toString());
        monitorLog.setFirstTime(startTime);
        monitorLog.setName(monitorName);
        monitorLog.setSerialNumber(s);


        //发送消息
//        String content = "";
//        content += "[{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"*BatchJobError*\"}},";
//        content += "{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"";
//        content += "*`ClassName：`* " + apiName + ";\\n";
//        content += "*`LogNumber：`* " + monitorLog.getId() + ";\\n";
//        content += "*`Time：`* " + startTime + ";\\n";
//        content += "*`CountNums：`* " + (successNums==null?"0":successNums+"") + ";\\n";
//        content += "*`FailNums：`* " + (failNums==null?"0":failNums+"") + ";\\n";
//        content += "\"}}]";

        JSONObject content = new JSONObject();
        content.put("ClassName",apiName);
        content.put("Time",startTime);
        content.put("CountNums",(successNums==null?"0":successNums+""));
        content.put("FailNums",(failNums==null?"0":failNums+""));
        monitorLog.setContent(content.toString());
        iMonitorLogService.insertMonitorLog(monitorLog);
        content.put("LogNumber",monitorLog.getId());
        asyncService.sendFeishu(monitorName,"BatchJobError",content);


        clearRedis(apiName);
    }
}
